﻿using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Threading;
using vncom.Models;

namespace vncom
{
    public class FileTypeFormatter : MediaTypeFormatter
    {
        public FileTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data")); 
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.Headers.HttpContentHeaders content, IFormatterLogger formatterLogger)
        {
            var taskCompletionSource = new TaskCompletionSource<object>();
            try
            {
                //HttpRequestMessage request = formatterLogger.Request;
                //string fileName = content.ContentDisposition.FileName;
                //string mediaType = content.ContentType.MediaType;
                MultipartParser parser = new MultipartParser(readStream);
                byte[] imagebuffer = ReadFully(readStream);
                var s = new Api_File(parser.Filename, parser.ContentType, parser.FileContents);
                taskCompletionSource.SetResult(s);
            }
            catch (Exception e)
            {
                taskCompletionSource.SetException(e);
            }

            return taskCompletionSource.Task;
        }

        private byte[] ReadFully(Stream input)
        {
            var Buffer = new byte[16 * 1024];
            using (var Ms = new MemoryStream())
            {
                int Read;
                while ((Read = input.Read(Buffer, 0, Buffer.Length)) > 0)
                {
                    Ms.Write(Buffer, 0, Read);
                }
                return Ms.ToArray();
            }
        }

        public override bool CanReadType(Type type)
        {
            return type == typeof(Api_File);
        }

        public override bool CanWriteType(Type type)
        {
            return false;
        }
    }
}